import 'dart:io';

import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:management/utils/log_utils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';
import 'package:dio/dio.dart';

///版本升级
class VersionUpgrade {
  static String? taskId;

  /// 获取apk存放地址(外部路径)
  static Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectory();
    return directory!.path;
  }

  ///安装app
  static Future<Null> _installApk() async {
    String path = await _apkLocalPath;
    await OpenFile.open(path + '/' + "app-release.apk");
  }

  /// 下载
  static Future<void> executeDownload() async {
    //apk存放路径
    final path = await _apkLocalPath;
    //获取版本
    var result = await Dio()
        .get("http://139.159.203.5:8080/apk/management/versionName")
        .catchError((e) {
      MyLog.e('获取版本号失败==》' + e.toString());
    });
    var apkName = 'app-release' + '.apk';
    File file = File(path + '/' + apkName);
    if (await file.exists()) await file.delete();

    //下载
    try {
      taskId = await FlutterDownloader.enqueue(
          url:
              'http://139.159.203.5:8080/apk/management/$result/app-release.apk',
          //下载最新apk的网络地址
          savedDir: path,
          //INTEGRATION
          fileName: apkName,
          showNotification: true,
          openFileFromNotification: true);
      FlutterDownloader.registerCallback(downloadCallBack);
    } on Exception catch (e) {
      MyLog.e(e.toString());
    }
  }

  static void downloadCallBack(
      String id, DownloadTaskStatus status, int progress) {
    // 当下载完成时，调用安装
    if (taskId == id && status == DownloadTaskStatus.complete) {
      _installApk();
    }
    if (status == DownloadTaskStatus.running) {
      print("下载中，请稍后...");
    }
  }
}
